import hashlib
import re
import time
import datetime


def reform_decimal(s, num=2):
    """
    # 四舍五入
    :param s: 小数字符串和 浮点数
    :param num: 保留位数
    :return: 返回浮点数
    """
    if not s:
        return 0.0
    if s != "None":
        result = round(float(s), num)
        return result
    else:
        return s


# 检查数据格式
def check_type(data):
    """
    查询数据类型
    :param data:
    :return: 返回字符串 如果未找到返回unknown
    """
    is_check = "unknown"
    if isinstance(data, int):
        is_check = "int"
    elif isinstance(data, str):
        is_check = "str"
    elif isinstance(data, float):
        is_check = "float"
    elif isinstance(data, list):
        is_check = "list"
    elif isinstance(data, tuple):
        is_check = "tuple"
    elif isinstance(data, dict):
        is_check = "dict"
    elif isinstance(data, set):
        is_check = "set"
    return is_check


# 获取 多少天以前的日期
def get_before_day(day, interval):
    """
        获取多少天以前的日期
        :param day: 日期格式：2023-01-01 空表示当天日期
        :param interval:  间隔多少周
        :return: 2023-01-01
        """
    if day == "":
        day = time_2_format(0, "%Y-%m-%d")
    timeArray = time.strptime(day, "%Y-%m-%d")
    timeStamp = int(time.mktime(timeArray)) - 3600 * 24 * interval
    timeArray = time.localtime(timeStamp)
    the_day = time.strftime("%Y-%m-%d", timeArray)
    return the_day


# 获取 多少天以后的日期
def get_after_day(day, interval):
    """
        获取多少天以后的日期
        :param day: 日期格式：2023-01-01 空表示当天日期
        :param interval:  间隔多少周
        :return: 2023-01-01
        """
    if day == "":
        day = time_2_format(0, "%Y-%m-%d")
    timeArray = time.strptime(day, "%Y-%m-%d")
    timeStamp = int(time.mktime(timeArray)) + 3600 * 24 * interval
    timeArray = time.localtime(timeStamp)
    the_day = time.strftime("%Y-%m-%d", timeArray)
    return the_day


def get_before_week(day, interval):
    """
    获取多少周以前的日期
    :param day: 日期格式：2023-01-01
    :param interval:  间隔多少周
    :return: 2023-01-01
    """
    interval = interval * 7
    theday = get_before_day(day, interval)
    week_list = week_get(theday)
    return week_list


def week_get(vdate):
    vdate = datetime.datetime.strptime(vdate, '%Y-%m-%d').date()
    dayscount = datetime.timedelta(days=vdate.isoweekday())
    dayfrom = vdate - dayscount + datetime.timedelta(days=1)
    week7 = []
    i = 0
    while (i <= 6):
        week7.append(str(dayfrom + datetime.timedelta(days=i)))
        i += 1
    return week7


def get_before_month_list(day, interval):
    """
    :param day: 日期格式：2023-01-01
    :param interval:  获取多少个月
    :return: 返回当前日期前面几个月1号的列表
    """
    for i in range(interval):
        day = get_before_month(day)
    return day


def get_before_month(day):
    """
    :param day: 日期格式：2023-01-01
    :return: 返回上一个月的1号
    """
    month_first = day[0:8] + "01"
    beforelast = get_before_day(month_first, 1)
    month_first = beforelast[0:8] + "01"
    return month_first


def format_num(num):
    """
    :param num: 需要转换的数字
    :return: 返回转换后带单位的字符串
    """
    if num >= 100000000:
        new_num = round(num / 1000000) / 100
        returnstr = str(new_num) + "亿"
    elif num >= 10000:
        new_num = round(num / 100) / 100
        returnstr = str(new_num) + "万"
    else:
        returnstr = str(num)
    return returnstr


# 时间格式转时间戳
# 格式如：2013-10-10 23:40:00 或 2013-10-10
def format_2_time(formattime):
    format = "%Y-%m-%d %H:%M:%S"
    if len(formattime) == 10:
        format = "%Y-%m-%d"
    if len(formattime) == 8:
        format = "%Y%m%d"
    timeArray = time.strptime(formattime, format)
    timeStamp = int(time.mktime(timeArray))
    return timeStamp


# 时间戳转时间格式
def time_2_format(time_stamp=0, format="%Y-%m-%d %H:%M:%S"):
    if int(time_stamp) <= 0:
        time_stamp = int(time.time())
    time_array = time.localtime(time_stamp)
    other_style_time = time.strftime(format, time_array)
    return other_style_time


# 检查手机号
def check_phone(phone):
    result = re.match(r"^1[356789]\d{9}$", phone)
    if result:
        return True
    else:
        return False


# 检查邮箱
def check_email(email):
    match_str = r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$'
    result = re.match(match_str, email)
    if result:
        return True
    else:
        return False


# 检查密码格式是否正确 大小写和数字特殊符号
def check_password(pwd, min=6, max=20):
    # 必须包含大小写和数字
    match_str = r'^(?=.*[a-z])(?=.*\d)(?=.*[A-Z])[A-Za-z\d#@!~%_^&*!]{'
    r = match_str + str(min) + ',' + str(max) + '}$'
    pattern = re.compile(r)
    if pattern.match(pwd):
        return True
    else:
        return False


# MD5加密
def md5(pwd):
    if pwd == "":
        return ""
    pwd_hash = hashlib.md5(pwd.encode('utf-8')).hexdigest()
    return pwd_hash
